package org.xiaojl.xcloud.tools.gateway.filter.route;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.xiaojl.xcloud.tools.gateway.kit.FilterKit;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import io.jmnarloch.spring.cloud.ribbon.support.RibbonFilterContextHolder;

/**  
 * <p>Title: GrayReleaseFilter</p>  
 *
 * <p>Description: 灰度发布过滤器</p>  
 *
 * @author jilong.xiao  
 * @date 2018年5月7日  
 */
@Component
public class GrayReleaseFilter extends ZuulFilter {
	private static final Logger log = LoggerFactory.getLogger(GrayReleaseFilter.class);
	
	@Override
	public boolean shouldFilter() {
		return FilterKit.isFilterFlag(RequestContext.getCurrentContext());
	}

	@Override
	public Object run() {
		RequestContext context = RequestContext.getCurrentContext();
		HttpServletRequest request = context.getRequest();
		String grayReleaseUser = request.getAttribute("grayReleaseUser")==null?"":request.getAttribute("grayReleaseUser").toString();
		//灰度示例
		RibbonFilterContextHolder.clearCurrentContext();
		//根据用户信息，判断是否进入灰度发布机器
		if(grayReleaseUser != null && "1".equals(grayReleaseUser)){//进入灰度发布的机器
			if(log.isDebugEnabled()){
				log.debug(String.format("[灰度发布机器] %s GrayReleaseFilter request to %s", request.getMethod(), request.getRequestURL().toString()));  
			}
			RibbonFilterContextHolder.getCurrentContext().add("gray-release", "true");
		}else{//进入正式发布的机器
			if(log.isDebugEnabled()){
				log.debug(String.format("[正式发布机器] %s GrayReleaseFilter request to %s", request.getMethod(), request.getRequestURL().toString()));  
			}
			RibbonFilterContextHolder.getCurrentContext().add("gray-release", "false");
		}
		
		return null;
	}

	@Override
	public String filterType() {
		return FilterConstants.ROUTE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 5;
	}

}
